﻿<template>
	<div class="card-fill layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<el-tabs v-model="activeTab">
				<el-tab-pane label="基本信息" name="main">
					<el-form ref="formRefFrameworkUser" :model="stateFrameworkUser.vmModel" label-width="120px">
						<el-row>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item
									ref="Entity_ITCode_FormItem"
									prop="Entity.ITCode"
									:label="$t('message.autotrans._Model_FrameworkUser_ITCode')"
									:rules="[
										{
											required: true,
											message: $t('message._system.common.vm.input', { input: $t('message.autotrans._Model_FrameworkUser_ITCode') }),
											trigger: 'blur',
										},
									]"
								>
									<el-input v-model="stateFrameworkUser.vmModel.Entity.ITCode" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item
									ref="Entity_Password_FormItem"
									prop="Entity.Password"
									:label="$t('message.autotrans._Model_FrameworkUser_Password')"
									:rules="[
										{
											required: true,
											message: $t('message._system.common.vm.input', { input: $t('message.autotrans._Model_FrameworkUser_Password') }),
											trigger: 'blur',
										},
									]"
								>
									<el-input v-model="stateFrameworkUser.vmModel.Entity.Password" clearable type="password"></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item
									ref="Entity_Name_FormItem"
									prop="Entity.Name"
									:label="$t('message.autotrans._Model_FrameworkUser_Name')"
									:rules="[
										{
											required: true,
											message: $t('message._system.common.vm.input', { input: $t('message.autotrans._Model_FrameworkUser_Name') }),
											trigger: 'blur',
										},
									]"
								>
									<el-input v-model="stateFrameworkUser.vmModel.Entity.Name" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item
									ref="Entity_IsValid_FormItem"
									prop="Entity.IsValid"
									:label="$t('message.autotrans._Model_FrameworkUser_IsValid')"
									:rules="[
										{
											required: true,
											message: $t('message._system.common.vm.input', { input: $t('message.autotrans._Model_FrameworkUser_IsValid') }),
											trigger: 'blur',
										},
									]"
								>
									<el-switch v-model="stateFrameworkUser.vmModel.Entity.IsValid" clearable></el-switch>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item ref="Entity_PhotoId_FormItem" prop="Entity.PhotoId" :label="$t('message.autotrans._Model_FrameworkUser_Photo')">
									<wtm-upload-image v-model="stateFrameworkUser.vmModel.Entity.PhotoId" clearable thumb-width="128" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item ref="Entity_CellPhone_FormItem" prop="Entity.CellPhone" :label="$t('message.autotrans._Model_FrameworkUser_CellPhone')">
									<el-input v-model="stateFrameworkUser.vmModel.Entity.CellPhone" clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>

						<!-- <el-row>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item
									ref="SelectedFrameworkUserGroupsIDs_FormItem"
									prop="SelectedFrameworkUserGroupsIDs"
									:label="$t('message.autotrans._AdminGroup')"
								>
									<el-cascader
										:options="stateFrameworkUser.AllFrameworkUserGroups"
										:props="{ multiple: true, checkStrictly: true, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
										filterable
										class="w100"
										v-model="stateFrameworkUser.vmModel.SelectedFrameworkUserGroupsIDs"
										clearable
									></el-cascader>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item
									ref="SelectedFrameworkUserRolesIDs_FormItem"
									prop="SelectedFrameworkUserRolesIDs"
									:label="$t('message.autotrans._AdminRole')"
								>
									<el-cascader
										:options="stateFrameworkUser.AllFrameworkUserRoles"
										:props="{ multiple: true, checkStrictly: true, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
										filterable
										class="w100"
										v-model="stateFrameworkUser.vmModel.SelectedFrameworkUserRolesIDs"
										clearable
									></el-cascader>
								</el-form-item>
							</el-col>
						</el-row> -->
					</el-form>
				</el-tab-pane>
				<el-tab-pane label="岗位信息" name="position" v-if="stateFrameworkUser.vmModel.Entity.ID">
					<SysUserJobPosition
						:key="stateFrameworkUser.vmModel.Entity.ID || ''"
						:search-bar="false"
						:toolbar="true"
						:is-disabled="true"
						:UserId="stateFrameworkUser.vmModel.Entity.ID"
					/>
				</el-tab-pane>
			</el-tabs>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message.autotrans._Page_AdminFrameworkUserCreate;false">
import { ElMessage, ElLoading } from 'element-plus';
import { reactive, ref, getCurrentInstance, onMounted, nextTick } from 'vue';
import { frameworkuserApi } from '/@/api/_admin/frameworkuser';
import other from '/@/utils/other';
import SysUserJobPosition from '/@/views/_admin/sysuserjobposition/index.vue';
import { IViewModel } from '/@/types/common';

// 常量定义
const BUTTON_TEXTS = {
	SAVE: '保存',
	CANCEL: '取消',
} as const;

const MESSAGE_TEXTS = {
	SAVE_SUCCESS: '保存成功',
} as const;

interface ISysFrameworkUser {
	ID: string | null;
	ITCode: string | null;
	Password: string | null;
	Name: string | null;
	IsValid: boolean;
	PhotoId: string | null;
	CellPhone: string | null;
}
interface ISysFrameworkUserVm {
	Entity: ISysFrameworkUser;
	SelectedFrameworkUserRolesIDs: string[];
	SelectedFrameworkUserGroupsIDs: string[];
}
// 定义变量内容
const ci = getCurrentInstance() as any;
const formRefFrameworkUser = ref();
const activeTab = ref('main');
const hasSavedOnce = ref(false);
const loading = ref(false);
const stateFrameworkUser = reactive<IViewModel<ISysFrameworkUserVm>>({
	vmModel: {
		Entity: {
			ID: null,
			ITCode: '',
			Password: '',
			Name: '',
			IsValid: true,
			PhotoId: null,
			CellPhone: null,
		},
		SelectedFrameworkUserRolesIDs: [],
		SelectedFrameworkUserGroupsIDs: [],
	},

	AllFrameworkUserRoles: [] as any[],
	AllFrameworkUserGroups: [] as any[],
});

// 统一的成功处理函数
const handleSuccess = (response: any) => {
	ElMessage.success(MESSAGE_TEXTS.SAVE_SUCCESS);
	emit('refresh');

	// 获取返回的ID并赋值，以便显示其他tabs
	if (response && response.Entity && response.Entity.ID) {
		stateFrameworkUser.vmModel.Entity = response.Entity;
	} else if (response && response.ID) {
		(stateFrameworkUser.vmModel.Entity as any).ID = response.ID;
	}

	hasSavedOnce.value = true;
	// 不关闭弹窗，让用户可以继续编辑其他tabs
	loading.value = false;

	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>) => {
	formRefFrameworkUser.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			apiCall().then(handleSuccess).catch(handleError);
		}
	});
};

// 取消
const onCloseFrameworkUser = () => {
	closeDialog();
};

// 提交
const onSubmitFrameworkUser = () => {
	handleApiRequest(() => {
		// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
		const submitData = JSON.parse(JSON.stringify(stateFrameworkUser.vmModel));
		if (!submitData.Entity.ID) {
			// 如果没有有效的 ID，删除该字段
			delete submitData.Entity.ID;
		}
		return frameworkuserApi().add(submitData);
	});
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	initializePageData();
	other.getSelectList('/api/_Admin/FrameworkUser/GetFrameworkRoles', [], false).then((x) => {
		stateFrameworkUser.AllFrameworkUserRoles = x;
	});
	other.getSelectList('/api/_Admin/FrameworkUser/GetFrameworkGroups?istree=true', [], true).then((x) => {
		stateFrameworkUser.AllFrameworkUserGroups = x;
	});
	loading.value = false;
	nextTick(() => {
		setupHeaderButtons();
	});
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);
// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		(stateFrameworkUser.vmModel.Entity as any).ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: 'primary',
			onClick: onSubmitFrameworkUser,
			visible: !hasSavedOnce.value, // 未保存过时显示保存按钮
		},
		{
			text: BUTTON_TEXTS.CANCEL,
			type: 'default',
			onClick: onCloseFrameworkUser,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};

// 暴露变量
defineExpose({});
</script>
